import axios from 'axios'
import { ElMessage } from 'element-plus'
type API_ENUM = {
  name: string,
  path: string | any,
  showMessage: boolean
}
export const service = ({ showMessage }: API_ENUM) => {
  const server = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 100000,
  })
  // 请求拦截器
  server.interceptors.request.use(
    (config) => {
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  server.interceptors.response.use(
    (response) => {

      if (response.data.data.success) {
        return response.data
      } else {
        ElMessage.error(response.data.msg)
        return Promise.reject(response.data)
      }
    },
    (error) => {
      if (!showMessage) return Promise.reject(showMessage)
      if (error.response.status === 401) {
        ElMessage.error(error.response.data.msg)
        return Promise.reject(error)
      }
      return Promise.reject(error)
    }
  )
  return server

}
